package com.cyzy.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyzy.dto.QuestionsDTO;
import com.cyzy.dto.R;
import com.cyzy.mapper.FavoriteMapper;
import com.cyzy.mapper.MistakeMapper;
import com.cyzy.mapper.QuestionsMapper;
import com.cyzy.service.ExamConfigService;
import com.cyzy.service.OptionsService;
import com.cyzy.service.QuestionsService;
import com.cyzy.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class QuestionsServiceImpl extends ServiceImpl<QuestionsMapper, Questions> implements QuestionsService {

    @Autowired
    private OptionsService optionsService;

    @Autowired
    private ExamConfigService examConfigService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private MistakeMapper mistakeMapper;

    @Autowired
    private QuestionsMapper questionsMapper;

    @Autowired
    private FavoriteMapper favoriteMapper;

    @Override
    public R getQuestionList(int userId, int examLibraryId,int currPage,int pageSize) {

        // 1. 创建分页对象，当前页为 pageNo，每页获取 pageSize 条数据
        Page<Questions> page = new Page<>(currPage, pageSize);

        // 2. 使用 QueryWrapper 进行条件查询
        QueryWrapper<Questions> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("exam_library_id", examLibraryId).eq("status", 1);

        // 3. 执行分页查询
        Page<Questions> questionPage = this.page(page, queryWrapper);

        if (questionPage.getRecords().isEmpty()) {
            return R.ok().code(500).message("没有找到相关题目");
        }

        QueryWrapper<UserFavoriteQuestions> favoriteQueryWrapper = new QueryWrapper<>();
        favoriteQueryWrapper.eq("user_id", userId).eq("exam_library_id", examLibraryId);
        List<UserFavoriteQuestions> favoriteList = favoriteMapper.selectList(favoriteQueryWrapper);

        // 提取收藏的题目ID列表
        List<Long> favoriteQuestionIds = favoriteList.stream()
                .map(UserFavoriteQuestions::getQuestionId)
                .collect(Collectors.toList());

        // 4. 为每个题目查询其对应的选项
        List<QuestionsDTO> questionDTOList = new ArrayList<>();
        for (Questions question : questionPage.getRecords()) {
            // 获取该题目对应的所有选项
            List<QuestionOptions> options = optionsService.getOptionsByQuestionId(question.getId());

            // 将题目和选项封装到 QuestionDTO 中
            QuestionsDTO questionDTO = new QuestionsDTO();
            questionDTO.setId(question.getId());
            questionDTO.setExamLibraryId(question.getExamLibraryId());
            questionDTO.setQuestionTypeId(question.getQuestionTypeId());
            questionDTO.setQuestionText(question.getQuestionText());
            questionDTO.setCorrectAnswer(question.getCorrectAnswer());
            questionDTO.setStatus(question.getStatus());
            questionDTO.setOptions(options); // 设置选项列表
            questionDTO.setIsFavorite(favoriteQuestionIds.contains(question.getId()) ? 1 : 0);

            // 将封装好的 QuestionDTO 加入到返回结果列表
            questionDTOList.add(questionDTO);
        }

        // 5. 返回封装好的数据，并携带分页信息
        return R.ok().data("questions", questionDTOList)
                .data("total", questionPage.getTotal()) // 返回总记录数
                .data("pages", questionPage.getPages()) // 返回总页数
                .data("current", questionPage.getCurrent()); // 当前页
    }

    @Override
    public R getQuestionListByRandom(int userId, int examLibraryId, int currPage, int pageSize) {
        System.out.println("获取随机题目");
        // Redis 键名
        String redisKey = "question-" + examLibraryId + "-list";

        // 1. 从 Redis 中获取题库的题目数量
        Long total = redisTemplate.opsForList().size(redisKey);  // 获取题库总题数
        System.out.println("total:" + total);
        if (total == null || total == 0) {
            // 如果 Redis 中没有题目列表，查询数据库并逐个存入 Redis
            List<Questions> questionsList = this.list(new QueryWrapper<Questions>()
                    .eq("exam_library_id", examLibraryId)
                    .eq("status", 1));

            if (questionsList.isEmpty()) {
                return R.ok().code(500).message("没有找到相关题目");
            }

            // 将题目数据逐条存入 Redis
            for (Questions question : questionsList) {
                List<QuestionOptions> options = optionsService.getOptionsByQuestionId(question.getId());
                QuestionsDTO questionDTO = new QuestionsDTO();
                questionDTO.setId(question.getId());
                questionDTO.setExamLibraryId(question.getExamLibraryId());
                questionDTO.setQuestionTypeId(question.getQuestionTypeId());
                questionDTO.setQuestionText(question.getQuestionText());
                questionDTO.setCorrectAnswer(question.getCorrectAnswer());
                questionDTO.setStatus(question.getStatus());
                questionDTO.setOptions(options); // 设置选项列表

                // 将每个题目逐个存入 Redis 列表
                redisTemplate.opsForList().rightPush(redisKey, questionDTO);
            }

            // 获取 Redis 中存储的题目数量
            total = (long) questionsList.size();
        }

        // 2. 获取 Redis 中指定范围的题目数据
        int startIndex = (currPage - 1) * pageSize;
        int endIndex = Math.min(currPage * pageSize, total.intValue());

        List<Object> questionDTOs = redisTemplate.opsForList().range(redisKey, startIndex, endIndex - 1);

        System.out.println("questionDTOs:" + questionDTOs);

        // 3. 将获取的题目数据打乱顺序
        Collections.shuffle(questionDTOs);

        // 4. 将获取的数据转换为 QuestionsDTO
        List<QuestionsDTO> result = new ArrayList<>();
        for (Object obj : questionDTOs) {
            QuestionsDTO questionsDTO =  new QuestionsDTO();
            questionsDTO = JSON.parseObject(obj.toString(), QuestionsDTO.class);
            result.add(questionsDTO);
        }
        System.out.println("result:" + result);

        QueryWrapper<UserFavoriteQuestions> favoriteQueryWrapper = new QueryWrapper<>();
        favoriteQueryWrapper.eq("user_id", userId).eq("exam_library_id", examLibraryId);
        List<UserFavoriteQuestions> favoriteList = favoriteMapper.selectList(favoriteQueryWrapper);

        // 提取收藏的题目ID列表
        List<Long> favoriteQuestionIds = favoriteList.stream()
                .map(UserFavoriteQuestions::getQuestionId)
                .collect(Collectors.toList());

        for (QuestionsDTO questionDTO : result) {
            questionDTO.setIsFavorite(favoriteQuestionIds.contains(questionDTO.getId()) ? 1 : 0);
        }

        // 5. 返回数据
        return R.ok().data("questions", result)
                .data("total", total); // 返回题库的总条数
    }

    @Override
    public R getQuestionListByType(int userId, int examLibraryId, int questionType, int currPage, int pageSize) {
        System.out.println("获取按题目类型顺序的题目");

        // Redis 键名，按题目类型维护不同的 Redis 列表
        String redisKey = "question-" + examLibraryId + "-type-" + questionType + "-list";

        // 1. 从 Redis 中获取指定题目类型的题目数量
        Long total = redisTemplate.opsForList().size(redisKey);  // 获取题库指定类型的题目数量
        System.out.println("total:" + total);
        if (total == null || total == 0) {
            // 如果 Redis 中没有题目列表，查询数据库并逐个存入 Redis
            List<Questions> questionsList = this.list(new QueryWrapper<Questions>()
                    .eq("exam_library_id", examLibraryId)
                    .eq("question_type_id", questionType) // 根据题目类型过滤
                    .eq("status", 1));

            if (questionsList.isEmpty()) {
                return R.ok().code(500).message("没有找到该类型的相关题目");
            }

            // 将题目数据逐条存入 Redis
            for (Questions question : questionsList) {
                List<QuestionOptions> options = optionsService.getOptionsByQuestionId(question.getId());
                QuestionsDTO questionDTO = new QuestionsDTO();
                questionDTO.setId(question.getId());
                questionDTO.setExamLibraryId(question.getExamLibraryId());
                questionDTO.setQuestionTypeId(question.getQuestionTypeId());
                questionDTO.setQuestionText(question.getQuestionText());
                questionDTO.setCorrectAnswer(question.getCorrectAnswer());
                questionDTO.setStatus(question.getStatus());
                questionDTO.setOptions(options); // 设置选项列表

                // 将每个题目逐个存入 Redis 列表
                redisTemplate.opsForList().rightPush(redisKey, questionDTO);
            }

            // 获取 Redis 中存储的题目数量
            total = (long) questionsList.size();
        }

        // 2. 获取 Redis 中指定范围的题目数据
        int startIndex = (currPage - 1) * pageSize;
        int endIndex = Math.min(currPage * pageSize, total.intValue());

        List<Object> questionDTOs = redisTemplate.opsForList().range(redisKey, startIndex, endIndex - 1);

        System.out.println("questionDTOs:" + questionDTOs);

        // 3. 将获取的题目数据按题目类型进行排序
        List<QuestionsDTO> sortedQuestions = new ArrayList<>();
        for (Object obj : questionDTOs) {
            QuestionsDTO questionsDTO = JSON.parseObject(obj.toString(), QuestionsDTO.class);
            sortedQuestions.add(questionsDTO);
        }

        // 按照题目类型进行排序（虽然这里按类型获取，实际上可以不排序）
//        sortedQuestions.sort((q1, q2) -> Integer.compare(q1.getQuestionTypeId(), q2.getQuestionTypeId()));

        QueryWrapper<UserFavoriteQuestions> favoriteQueryWrapper = new QueryWrapper<>();
        favoriteQueryWrapper.eq("user_id", userId).eq("exam_library_id", examLibraryId);
        List<UserFavoriteQuestions> favoriteList = favoriteMapper.selectList(favoriteQueryWrapper);

        // 提取收藏的题目ID列表
        List<Long> favoriteQuestionIds = favoriteList.stream()
                .map(UserFavoriteQuestions::getQuestionId)
                .collect(Collectors.toList());

        for (QuestionsDTO questionDTO : sortedQuestions) {
            questionDTO.setIsFavorite(favoriteQuestionIds.contains(questionDTO.getId()) ? 1 : 0);
        }

        // 4. 返回数据
        return R.ok().data("questions", sortedQuestions)
                .data("total", total) // 返回题库指定类型的总条数
                .data("current", currPage) // 当前页
                .data("pages", (total + pageSize - 1) / pageSize); // 总页数
    }

    @Override
    public R getQuestionData(int examLibraryId) {
        // Redis 键名
        String redisKey = "question-" + examLibraryId + "-list";


        // 1. 从 Redis 中获取题库的题目数量
        Long total = redisTemplate.opsForList().size(redisKey);  // 获取题库总题数
        System.out.println("total:" + total);
        if (total == null || total == 0) {
            // 如果 Redis 中没有题目列表，查询数据库并逐个存入 Redis
            List<Questions> questionsList = this.list(new QueryWrapper<Questions>()
                    .eq("exam_library_id", examLibraryId)
                    .eq("status", 1));

            if (questionsList.isEmpty()) {
                return R.ok().code(500).message("没有找到相关题目").data("total",total).data("singleTotal",0).data("mutipleTotal",0).data("trueOrFalseTotal",0);
            }

            // 将题目数据逐条存入 Redis
            for (Questions question : questionsList) {
                List<QuestionOptions> options = optionsService.getOptionsByQuestionId(question.getId());
                QuestionsDTO questionDTO = new QuestionsDTO();
                questionDTO.setId(question.getId());
                questionDTO.setExamLibraryId(question.getExamLibraryId());
                questionDTO.setQuestionTypeId(question.getQuestionTypeId());
                questionDTO.setQuestionText(question.getQuestionText());
                questionDTO.setCorrectAnswer(question.getCorrectAnswer());
                questionDTO.setStatus(question.getStatus());
                questionDTO.setOptions(options); // 设置选项列表

                // 将每个题目逐个存入 Redis 列表
                redisTemplate.opsForList().rightPush(redisKey, questionDTO);
            }

            // 获取 Redis 中存储的题目数量
            total = (long) questionsList.size();
        }

        // Redis 键名：不同类型的题目分别存储
        String redisKeySingle = "question-" + examLibraryId + "-type-1-list"; // 单选题
        String redisKeyMultiple = "question-" + examLibraryId + "-type-2-list"; // 多选题
        String redisKeyTrueFalse = "question-" + examLibraryId + "-type-3-list"; // 判断题

        // 1. 从 Redis 中获取单选题、多选题和判断题的题目数量
        Long totalSingle = redisTemplate.opsForList().size(redisKeySingle);
        Long totalMultiple = redisTemplate.opsForList().size(redisKeyMultiple);
        Long totalTrueFalse = redisTemplate.opsForList().size(redisKeyTrueFalse);

        // 2. 如果 Redis 中没有相应题目列表，查询数据库并存入 Redis
        // 仅当 Redis 中没有存储过该类型题目时，才从数据库查询并存入 Redis
        if (totalSingle == null || totalSingle == 0) {
            // 查询数据库并将单选题存入 Redis
            List<Questions> singleQuestions = this.list(new QueryWrapper<Questions>()
                    .eq("exam_library_id", examLibraryId)
                    .eq("question_type_id", 1) // 单选题
                    .eq("status", 1));

            if (!singleQuestions.isEmpty()) {
                for (Questions question : singleQuestions) {
                    List<QuestionOptions> options = optionsService.getOptionsByQuestionId(question.getId());
                    QuestionsDTO questionDTO = new QuestionsDTO();
                    questionDTO.setId(question.getId());
                    questionDTO.setExamLibraryId(question.getExamLibraryId());
                    questionDTO.setQuestionTypeId(question.getQuestionTypeId());
                    questionDTO.setQuestionText(question.getQuestionText());
                    questionDTO.setCorrectAnswer(question.getCorrectAnswer());
                    questionDTO.setStatus(question.getStatus());
                    questionDTO.setOptions(options);

                    // 将每个单选题存入 Redis
                    redisTemplate.opsForList().rightPush(redisKeySingle, questionDTO);
                }
            }
            // 更新 Redis 中单选题的数量
            totalSingle = (long) singleQuestions.size();
        }

        if (totalMultiple == null || totalMultiple == 0) {
            // 查询数据库并将多选题存入 Redis
            List<Questions> multipleQuestions = this.list(new QueryWrapper<Questions>()
                    .eq("exam_library_id", examLibraryId)
                    .eq("question_type_id", 2) // 多选题
                    .eq("status", 1));

            if (!multipleQuestions.isEmpty()) {
                for (Questions question : multipleQuestions) {
                    List<QuestionOptions> options = optionsService.getOptionsByQuestionId(question.getId());
                    QuestionsDTO questionDTO = new QuestionsDTO();
                    questionDTO.setId(question.getId());
                    questionDTO.setExamLibraryId(question.getExamLibraryId());
                    questionDTO.setQuestionTypeId(question.getQuestionTypeId());
                    questionDTO.setQuestionText(question.getQuestionText());
                    questionDTO.setCorrectAnswer(question.getCorrectAnswer());
                    questionDTO.setStatus(question.getStatus());
                    questionDTO.setOptions(options);

                    // 将每个多选题存入 Redis
                    redisTemplate.opsForList().rightPush(redisKeyMultiple, questionDTO);
                }
            }
            // 更新 Redis 中多选题的数量
            totalMultiple = (long) multipleQuestions.size();
        }

        if (totalTrueFalse == null || totalTrueFalse == 0) {
            // 查询数据库并将判断题存入 Redis
            List<Questions> trueFalseQuestions = this.list(new QueryWrapper<Questions>()
                    .eq("exam_library_id", examLibraryId)
                    .eq("question_type_id", 3) // 判断题
                    .eq("status", 1));

            if (!trueFalseQuestions.isEmpty()) {
                for (Questions question : trueFalseQuestions) {
                    List<QuestionOptions> options = optionsService.getOptionsByQuestionId(question.getId());
                    QuestionsDTO questionDTO = new QuestionsDTO();
                    questionDTO.setId(question.getId());
                    questionDTO.setExamLibraryId(question.getExamLibraryId());
                    questionDTO.setQuestionTypeId(question.getQuestionTypeId());
                    questionDTO.setQuestionText(question.getQuestionText());
                    questionDTO.setCorrectAnswer(question.getCorrectAnswer());
                    questionDTO.setStatus(question.getStatus());
                    questionDTO.setOptions(options);

                    // 将每个判断题存入 Redis
                    redisTemplate.opsForList().rightPush(redisKeyTrueFalse, questionDTO);
                }
            }
            // 更新 Redis 中判断题的数量
            totalTrueFalse = (long) trueFalseQuestions.size();
        }

        QueryWrapper<ExamQuestionConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("exam_library_id", examLibraryId).eq("status", 1); // 查询有效的配置

        // 获取题库配置
        ExamQuestionConfig config = examConfigService.getOne(queryWrapper);
        int result;
        if(config == null){
            result = 0;
        }else {
            result = 1;
        }

        // 5. 返回数据
        return R.ok().data("total", total).data("singleTotal", totalSingle).data("multipleTotal", totalMultiple).data("trueFalseTotal", totalTrueFalse)
                .data("config", result); // 返回题库的总条数

    }

    @Override
    public R getQuestionListByExam(int examLibraryId) {
        // 使用 MyBatis-Plus 查询题库配置表获取题目数量和分数
        QueryWrapper<ExamQuestionConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("exam_library_id", examLibraryId).eq("status", 1); // 查询有效的配置

        // 获取题库配置
        ExamQuestionConfig config = examConfigService.getOne(queryWrapper);

        if (config == null) {
            return R.ok().code(500).message("题库配置不存在或已失效");
        }

        // Redis 键名：根据不同题型存储不同的 Redis 列表
        String redisKeySingle = "question-" + examLibraryId + "-type-1-list"; // 单选题
        String redisKeyMultiple = "question-" + examLibraryId + "-type-2-list"; // 多选题
        String redisKeyTrueFalse = "question-" + examLibraryId + "-type-3-list"; // 判断题

        // 获取 Redis 中的题目数量
        Long totalSingle = redisTemplate.opsForList().size(redisKeySingle);  // 单选题
        Long totalMultiple = redisTemplate.opsForList().size(redisKeyMultiple);  // 多选题
        Long totalTrueFalse = redisTemplate.opsForList().size(redisKeyTrueFalse);  // 判断题

//        if (totalSingle == null || totalSingle == 0 || totalMultiple == null || totalMultiple == 0 || totalTrueFalse == null || totalTrueFalse == 0) {
//            return R.error().message("题库数据不足，无法生成模拟考试题目");
//        }

        // 随机获取指定数量的题目
        List<QuestionsDTO> selectedQuestions = new ArrayList<>();

        // 从 Redis 中获取题目数据
        if(totalSingle != null && totalSingle != 0){
            List<Object> singleQuestions = redisTemplate.opsForList().range(redisKeySingle, 0, totalSingle - 1);
            // 随机打乱各题型的题目
            Collections.shuffle(singleQuestions);
            // 从单选题中选20题
            for (int i = 0; i < Math.min(config.getSingleChoiceCount(), singleQuestions.size()); i++) {
                selectedQuestions.add(JSON.parseObject(singleQuestions.get(i).toString(), QuestionsDTO.class));
            }
        }
        if(totalMultiple != null && totalMultiple != 0){
            List<Object> multipleQuestions = redisTemplate.opsForList().range(redisKeyMultiple, 0, totalMultiple - 1);
            Collections.shuffle(multipleQuestions);
            // 从多选题中选10题
            for (int i = 0; i < Math.min(config.getMultipleChoiceCount(), multipleQuestions.size()); i++) {
                selectedQuestions.add(JSON.parseObject(multipleQuestions.get(i).toString(), QuestionsDTO.class));
            }

        }
        if(totalTrueFalse != null && totalTrueFalse != 0){
            List<Object> trueFalseQuestions = redisTemplate.opsForList().range(redisKeyTrueFalse, 0, totalTrueFalse - 1);
            Collections.shuffle(trueFalseQuestions);
            // 从判断题中选15题
            for (int i = 0; i < Math.min(config.getTrueOrFalseCount(), trueFalseQuestions.size()); i++) {
                selectedQuestions.add(JSON.parseObject(trueFalseQuestions.get(i).toString(), QuestionsDTO.class));
            }
        }



        // 返回模拟考试题目
        return R.ok().data("total", selectedQuestions.size()).data("questions", selectedQuestions)
                .data("singleChoiceScore", config.getSingleChoiceScore())
                .data("multipleChoiceScore", config.getMultipleChoiceScore())
                .data("trueOrFalseScore", config.getTrueOrFalseScore())
                .data("totalScore", config.getTotalScore());
    }

    @Override
    public R getQuestionListByMistake(int userId, int examLibraryId) {
        // 1. 使用 MyBatis-Plus 的 QueryWrapper 查询错题记录中的 questionId
        QueryWrapper<UserMistakeQuestions> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("exam_library_id", examLibraryId);

        // 查询错题表，获取 questionId 列表
        List<UserMistakeQuestions> mistakeQuestions = mistakeMapper.selectList(queryWrapper);

        if (mistakeQuestions.isEmpty()) {
            return R.ok().code(500).message("没有找到相关错题记录").data("total", 0);
        }

        /// 获取所有错题记录中的 questionId
        List<Long> questionIds = new ArrayList<>();
        for (UserMistakeQuestions mistake : mistakeQuestions) {
            questionIds.add(mistake.getQuestionId());
        }

        // 2. 根据 questionIds 获取题目信息
        // 使用 QueryWrapper 直接查询所有题目
        QueryWrapper<Questions> questionsQueryWrapper = new QueryWrapper<>();
        questionsQueryWrapper.in("id", questionIds); // 根据 questionIds 查询所有题目
        List<Questions> questionsList = questionsMapper.selectList(questionsQueryWrapper);

        if (questionsList.isEmpty()) {
            return R.ok().code(500).message("没有找到相关题目信息").data("total", 0);
        }

        // 3. 为每个题目查询对应的选项
        List<QuestionsDTO> questionDTOList = new ArrayList<>();
        for (Questions question : questionsList) {
            // 获取该题目对应的所有选项
            List<QuestionOptions> options = optionsService.getOptionsByQuestionId(question.getId());

            // 将题目和选项封装到 QuestionDTO 中
            QuestionsDTO questionDTO = new QuestionsDTO();
            questionDTO.setId(question.getId());
            questionDTO.setExamLibraryId(question.getExamLibraryId());
            questionDTO.setQuestionTypeId(question.getQuestionTypeId());
            questionDTO.setQuestionText(question.getQuestionText());
            questionDTO.setCorrectAnswer(question.getCorrectAnswer());
            questionDTO.setStatus(question.getStatus());
            questionDTO.setOptions(options); // 设置选项列表

            // 将封装好的 QuestionDTO 加入到返回结果列表
            questionDTOList.add(questionDTO);
        }

        // 4. 返回封装好的数据
        return R.ok().data("questions", questionDTOList).data("total", questionDTOList.size());
    }

    @Override
    public R getQuestionListByFavorite(int userId, int examLibraryId) {
        // 1. 使用 MyBatis-Plus 的 QueryWrapper 查询错题记录中的 questionId
        QueryWrapper<UserFavoriteQuestions> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("exam_library_id", examLibraryId);

        // 查询错题表，获取 questionId 列表
        List<UserFavoriteQuestions> favoriteQuestions = favoriteMapper.selectList(queryWrapper);

        if (favoriteQuestions.isEmpty()) {
            return R.ok().code(500).message("没有找到相关收藏记录").data("total", 0);
        }

        /// 获取所有错题记录中的 questionId
        List<Long> questionIds = new ArrayList<>();
        for (UserFavoriteQuestions favorite : favoriteQuestions) {
            questionIds.add(favorite.getQuestionId());
        }

        // 2. 根据 questionIds 获取题目信息
        // 使用 QueryWrapper 直接查询所有题目
        QueryWrapper<Questions> questionsQueryWrapper = new QueryWrapper<>();
        questionsQueryWrapper.in("id", questionIds); // 根据 questionIds 查询所有题目
        List<Questions> questionsList = questionsMapper.selectList(questionsQueryWrapper);

        if (questionsList.isEmpty()) {
            return R.ok().code(500).message("没有找到相关题目信息").data("total", 0);
        }

        QueryWrapper<UserFavoriteQuestions> favoriteQueryWrapper = new QueryWrapper<>();
        favoriteQueryWrapper.eq("user_id", userId).eq("exam_library_id", examLibraryId);
        List<UserFavoriteQuestions> favoriteList = favoriteMapper.selectList(favoriteQueryWrapper);

        // 提取收藏的题目ID列表
        List<Long> favoriteQuestionIds = favoriteList.stream()
                .map(UserFavoriteQuestions::getQuestionId)
                .collect(Collectors.toList());

        // 3. 为每个题目查询对应的选项
        List<QuestionsDTO> questionDTOList = new ArrayList<>();
        for (Questions question : questionsList) {
            // 获取该题目对应的所有选项
            List<QuestionOptions> options = optionsService.getOptionsByQuestionId(question.getId());

            // 将题目和选项封装到 QuestionDTO 中
            QuestionsDTO questionDTO = new QuestionsDTO();
            questionDTO.setId(question.getId());
            questionDTO.setExamLibraryId(question.getExamLibraryId());
            questionDTO.setQuestionTypeId(question.getQuestionTypeId());
            questionDTO.setQuestionText(question.getQuestionText());
            questionDTO.setCorrectAnswer(question.getCorrectAnswer());
            questionDTO.setStatus(question.getStatus());
            questionDTO.setOptions(options); // 设置选项列表
            questionDTO.setIsFavorite(favoriteQuestionIds.contains(question.getId()) ? 1 : 0);

            // 将封装好的 QuestionDTO 加入到返回结果列表
            questionDTOList.add(questionDTO);
        }

        // 4. 返回封装好的数据
        return R.ok().data("questions", questionDTOList).data("total", questionDTOList.size());
    }


}
